using System;
using System.Collections.Generic;
class Graph
{
private int V;
private List<int>[] adj;
public Graph(int v)
{
V = v;
adj = new List<int>[v];
for (int i = 0; i < v; ++i)
{
adj[i] = new List<int>();
}
}
public void AddEdge(int v, int w)
{
adj[v].Add(w);
}
public void BFS(int s)
{
bool[] visited = new bool[V];
Queue<int> queue = new Queue<int>();
visited[s] = true;
queue.Enqueue(s);
while (queue.Count != 0)
{
s = queue.Dequeue();
Console.Write(s + " ");
foreach (int i in adj[s])
{
if (!visited[i])
{
visited[i] = true;
queue.Enqueue(i);
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
Graph g = new Graph(7);
g.AddEdge(0, 1);
g.AddEdge(0, 2);
g.AddEdge(1, 3);
g.AddEdge(1, 4);
g.AddEdge(2, 5);
g.AddEdge(2, 6);
Console.WriteLine("從節點0開始的廣度優先搜尋結果:");
g.BFS(0);
}
}
期望挑戰30天持續更新成功 ~ DAY25